#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/time.h>


int main(int argv, char *argc[])
{
	int sock;
	int restul;
	socklen_t addr_lenght;
	struct sockaddr_in client_addr;
	struct sockaddr_in server_addr;
	char buffer[100];
	char *ip = "0.0.0.0";
	char *port = "43200";
	
	if(argv > 1)
		ip = argc[1];
	if(argv > 2)
		port = argc[2];
	
	//创建套接字
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if(sock == -1)
	{
		perror("socket");
		return -1;
	}
	
	//绑IP和端口
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(port));
	server_addr.sin_addr.s_addr = inet_addr(ip);
	restul = bind(sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
	if(restul == -1)
	{
		close(sock);
		perror("bind");
		return -1;
	}
	printf("IP %s; port %d\n", inet_ntoa(server_addr.sin_addr), ntohs(server_addr.sin_port));
	
	while(1)
	{
		//读客户端发送过来的数据
		memset(buffer, 0, sizeof(buffer));
		addr_lenght = sizeof(client_addr);
		restul = recvfrom(sock, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&client_addr, &addr_lenght);
		if(restul == -1)
		{
			close(sock);
			perror("recvfrom");
			return -1;
		}
		
		//把数据返回客户端
		if(sendto(sock, buffer, restul, 0, (struct sockaddr*)&client_addr, sizeof(client_addr)) == -1)
		{
			close(sock);
			perror("sendto");
			return -1;
		}
	}
}
